package me.xue.communityhealth.service;

import com.github.pagehelper.Page;
import lombok.extern.log4j.Log4j2;
import me.xue.communityhealth.exception.IllegalRequestException;
import me.xue.communityhealth.exception.ObjectNotFoundException;
import me.xue.communityhealth.model.Staff;
import me.xue.communityhealth.repo.StaffRepository;
import me.xue.communityhealth.util.ApplicationUtil;
import me.xue.communityhealth.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@Service
@Log4j2
public class StaffService implements BaseService<Staff, Integer> {

    private final StaffRepository staffRepository;

    @Autowired
    public StaffService(StaffRepository staffRepository) {
        this.staffRepository = staffRepository;
    }

    @Override
    public int save(Staff staff) {
        return staffRepository.save(staff);
    }

    @Override
    public int update(Staff staff) {
        return staffRepository.update(staff);
    }

    @Override
    public int delete(Integer which) {
        return (which == null || which < 0) ? 0 : staffRepository.delete(which);
    }

    @Override
    public List<Staff> findAll() {
        return null;
    }

    public Staff findStaff(Integer id) {
        if (id == null || id < 0) {
            throw new IllegalRequestException();
        }
        Staff staff = staffRepository.findOne(id);
        if (staff == null) {
            throw new ObjectNotFoundException();
        }
        return staff;
    }

    public Page<Staff> pagedPatients(Integer page) {
        if (page == null || page < 1) {
            throw new IllegalRequestException();
        }
        return staffRepository.pagedStaffs();
    }

    public String savePortrait(MultipartFile multipartFile, String fileName) {
        if (multipartFile == null || multipartFile.isEmpty()) {
            return null;
        }
        return FileUtil.saveMultipartFile(multipartFile, ApplicationUtil.getPortraitPath().getAbsolutePath(), fileName);
    }

    public void deletePortrait(String fileName) {
        File file = new File(ApplicationUtil.getPortraitPath().getPath(), fileName);
        if (file.exists()) {
            try {
                Files.delete(Paths.get(ApplicationUtil.getPortraitPath().getPath(), fileName));
            } catch (IOException e) {
                log.error("删除员工图片失败", e);
            }
        }
    }
}
